<template>
  <div class="goods-list-container">
    <!-- 搜索和操作栏 -->
    <div class="action-bar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称/SKU"
          clearable
          style="width: 300px"
          @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch"/>
        </template>
      </el-input>

      <el-button type="primary" :icon="Plus" @click="handleCreate(false)">新增商品</el-button>
    </div>

    <!-- 商品数据表格 -->
    <el-table
        :data="paginatedData"
        stripe
        style="width: 100%"
        height="calc(100vh - 220px)"
    >
      <el-table-column prop="sku" label="商品编码" width="180" fixed/>
      <el-table-column label="商品图" width="120">
        <template #default="{ row }">
          <el-image
              :src="row.productImage"
              :preview-src-list="[row.productImage]"
              fit="cover"
              style="width: 60px; height: 60px"
              :preview-teleported="true"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="商品名称" width="280"/>
      <el-table-column label="分类" width="150">
        <template #default="{ row }">
          {{row.categoryName.name}}
        </template>
      </el-table-column>
      <el-table-column label="品牌" width="150">
        <template #default="{ row }">
          {{ row.brandName.name }}
        </template>
      </el-table-column>
      <el-table-column label="库存" width="120">
        <template #default="{ row }">
          <span :class="{ 'text-red-500': row.stock < 10 }">{{ row.stock }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建信息" width="200">
        <template #default="{ row }">
          <div class="text-xs">
            <div>创建人: {{ row.createdName }}</div>
            <div>{{ formatTime(row.createdAT) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleCreate(true, row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="filteredData.length"
          :page-sizes="[9, 15, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
      />
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑商品' : '新增商品'"
        width="600px"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品编码" prop="sku">
          <el-input v-model="formData.sku" placeholder="请输入商品SKU" />
        </el-form-item>

        <el-form-item label="商品分类" prop="category_id">
          <el-select
              v-model="formData.categoryId"
              placeholder="请选择分类"
              style="width: 100%"
          >
            <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品品牌" prop="brand_id">
          <el-select
              v-model="formData.brandId"
              placeholder="请选择品牌"
              style="width: 100%"
          >
            <el-option
                v-for="item in brands"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="库存数量" prop="stock">
          <el-input-number
              v-model="formData.stock"
              :min="0"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="商品图片">
          <el-upload
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleImageUpload"
          >
            <el-image
                v-if="formData.productImage"
                :src="formData.productImage"
                class="preview-image"
                fit="cover"
            />
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {addProduct, deleteProduct, getAllBrands, getAllCategories, getAllProducts, updateProduct} from "@/api/auth.js";
import {Plus, Search} from "@element-plus/icons-vue";
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
// 表单初始数据
const initFormData = () => ({
  id: null,
  name: '',
  sku: '',
  categoryId: null,
  brandId: null,
  stock: 1,
  productImage: ''
})

const formData = reactive(initFormData())
// 表单验证规则
const formRules = reactive({
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  sku: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  brandId: [{ required: true, message: '请选择品牌', trigger: 'change' }]
})
// 打开弹窗
const handleCreate = (isEdit, rowData) => {

  isEditMode.value = isEdit
  if (isEdit) {
    Object.assign(formData, rowData)
    formData.brandId = rowData.brandName.id
    formData.categoryId = rowData.categoryName.id
  } else {
    Object.assign(formData, initFormData())
  }
  dialogVisible.value = true
}

// 图片上传处理
const handleImageUpload = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.productImage = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 提交表单
const submitForm = async () => {

  try {
    await formRef.value.validate()

    // 模拟API请求
    if (isEditMode.value) {

      try {
        const res=await updateProduct(formData)
        if(res.code===200){
          ElMessage.success('商品修改成功')
          await initData()
        }else {
          ElMessage.error(res.message)
        }
      }catch (e){
        ElMessage.error(e)
      }

    } else {
      const res=await addProduct(formData)
     try {
       if(res.code===200){
         ElMessage.success('商品添加成功')
         await initData()
       }else {
         ElMessage.error(res.message)
       }
     }
     catch (e){
        ElMessage.error('未知错误请联系管理员')
     }


    }

    dialogVisible.value = false
  } catch (error) {
    ElMessage.warning('请完善表单信息')
  }
}
// 模拟数据配置
const categories = ref([
  {id: 1, name: '手机数码'},
  {id: 2, name: '家用电器'},
  {id: 3, name: '服饰鞋包'}
])

const brands = ref([
  {id: 1, name: '苹果'},
  {id: 2, name: '华为'},
  {id: 3, name: '小米'},
  {id: 4, name: '美的'}
])

const users = ref([
  {id: 1, username: 'admin'},
  {id: 2, username: 'manager'},
  {id: 3, username: 'operator'}
])

// 生成100条商品测试数据
const generateGoods = () => {
  const goodsArray = [];

    goodsArray.push({
      id: 1,
      sku: `SKU`,
      name: `商品名称`,
      productImage: `https://picsum.photos/100/100?random=`,
      categoryName: {id: 1, name: '手机数码'},
      stock: Math.floor(Math.random() * 50),
      brandName: {id: 1, name: '手机数码'},
      createdNme: '周兴',
      createdAt: new Date(2024, 0,1 ).toISOString(),
    });

  return goodsArray;
}
const initData = async () => {
  try {
    const res = await getAllProducts()
    if (res.code === 200) {
      rawData.value = res.data
    } else {
      ElMessage.error('获取商品列表失败')
    }
  } catch (error) {
    ElMessage.error('未知错误请联系管理员')
  }
  try {
    const res=await getAllCategories()
    if(res.code===200){
      categories.value=res.data
    }else {
      ElMessage.error('获取分类列表失败')
    }
  }catch (error){
    ElMessage.error('未知错误请联系管理员')
  }
  try {
    const res=await getAllBrands()
    if(res.code===200){
      brands.value=res.data
    }else {
      ElMessage.error('获取品牌列表失败')
    }
  }catch (e){
    ElMessage.error('未知错误请联系管理员')
  }

}
onMounted(()=>{
  initData()
})

// 数据状态
const rawData = ref(generateGoods())
const searchKeyword = ref('')

// 关联数据映射
const categoryMap = computed(() =>
    categories.value.reduce((map, item) => (map[item.id] = item, map), {}))

const brandMap = computed(() =>
    brands.value.reduce((map, item) => (map[item.id] = item, map), {}))

const userMap = computed(() =>
    users.value.reduce((map, item) => (map[item.id] = item, map), {}))

// 分页配置
const pagination = reactive({
  current: 1,
  size: 9
})

// 过滤后的数据
const filteredData = computed(() => {
  const keyword = searchKeyword.value.toLowerCase()
  return rawData.value.filter(item =>
      item.name.toLowerCase().includes(keyword) ||
      item.sku.toLowerCase().includes(keyword)
  )
})

// 分页数据
const paginatedData = computed(() => {
  const start = (pagination.current - 1) * pagination.size
  return filteredData.value.slice(start, start + pagination.size)
})

// 时间格式化
const formatTime = (time) => {
  return new Date(time).toLocaleDateString() + ' ' +
      new Date(time).toLocaleTimeString().slice(0, 5)
}



const handleEdit = (row) => {
  ElMessage.info(`编辑商品：${row.name}`)
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除 ${row.name}？`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const res=deleteProduct(row.id)
    console.log(res)

      ElMessage.success('删除成功')
      initData()

  }).catch(() => null)
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
}
</script>

<style scoped>
.goods-list-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  .action-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .text-red-500 {
    color: #f56c6c;
    font-weight: bold;
  }

  :deep(.el-image__inner) {
    border-radius: 4px;
  }
}
.preview-image {
  width: 200px;
  height: 200px;
  border-radius: 4px;
  cursor: pointer;
}

.upload-icon {
  width: 200px;
  height: 200px;
  font-size: 28px;
  color: #8c939d;
  background: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
</style>